<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
        "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head>
  <title>TOUPROPRE DBMS</title>
	<meta http-equiv="content-type" content="text/html; charset=utf-8" />
    <link rel="stylesheet" media="screen" type="text/css" title="Design" href="styles/design.css" />
</head>

<body>
    <!-- TITLE  -->
	<div id="page_title">
      <h1>Back-up system</h1>
    </div>

    <!-- Side Menues -->
    <?php include "tools/Menues.html"; ?>

    <!-- Main Body -->
    <div id="page_body">
<?php
/**
 * Includes :
 */
include "tools/Forms.php";

/*
 * Function Definitions :
 */
function getFileName($tablename) {
    if(!isset($_POST[$tablename]) OR $_POST[$tablename]=='') {
        return 'back/'.$tablename.'.csv';
    }
    else {
        return $tablename;
    }
}
function exportcsv($tablename) {
    global $dlm, $nlc;
    $filename = getFileName($tablename);
    $sql = "SELECT * FROM ".$tablename." INTO OUTFILE '".$filename."' ".
        "FIELDS TERMINATED BY '".$dlm."' OPTIONALLY ENCLOSED BY '\"' ".
        "ESCAPED BY \"\\\\\" ".
        "LINES TERMINATED BY '".$nlc."'";
    echo '<p class="sql_cmd">'.$sql.'</p>';
    $response = mysql_query($sql); 
    if($response) {
        echo '<p class="text">Exported '.$tablename.' to '.$filename.'</p>';
    }
    else {
        echo "<p class=sql_error>".mysql_error()."</p>";
    }
}

/*
 * Behaviour :
 */
if(isset($_POST['submit'])) {
    // Get Delimiter and New Line Character :
    if($_POST['dlm']!='') {
        $dlm = str_replace("\\t","\t",$_POST['dlm']);
    }
    else {$dlm = ';';}
    if($_POST['nlc']!='') {
        $nlc = str_replace("\\r","\r",$_POST['nlc']);
        $nlc = str_replace("\\n","\n",$_POST['nlc']);
    }
    else {$nlc = '\r';}
    
    // Get Filenames :
    include "tools/connect.php";
    exportcsv("clients");
    exportcsv("suppliers");
    exportcsv("items");
    exportcsv("sales");
    exportcsv("itemsSold");
    exportcsv("purchases");
    exportcsv("itemsPurchased");
    exportcsv("facilities");
    exportcsv("itemStock");
    mysql_close();
 }
 else {
     echo '<p class="text">The page will allow you to back up your database.</p>';
     echo '<p class="text">Enter the filenames in which you want to save'.
         'your data. You can leave fields blank in which case default values'.
         'will be used. The default values are "back/[NAME_OF_TABLE].csv" for the '.
         'files, ";" for the delimiter and "\\r" for the newline character.</p>';
     EchoCSVForm('backup.php', 'submit','Export');
     
 }
?>  
    </div>
    
    <!-- Footer -->
    <?php include "tools/Footer.html"; ?>
</body>
</html>
